package com.loveto.service;

import java.io.UnsupportedEncodingException;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.loveto.common.JsonUtils;
import com.loveto.constant.LovetoConstant;

public class OpenTournamentQuestionIndirectDetailActivity extends BaseActivity implements
View.OnClickListener{
	
	// 사용하는 변수들
	private Intent intentMoveToPage;
	private int presentInputRound;
	private LinearLayout contentMain;
	private Handler myHandler = new Handler();
	private ProgressDialog progressDialog; // 프로그레스다이얼로그
	private String presentHighCategory;
	private String presentLowCategory;
	private String presentLowCategoryName;
	private String presentQuestionText;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.loveto_open_tournament_question_indirect_detail);
		
		//초기화
		contentMain = (LinearLayout) findViewById(R.id.content_main);
		progressDialog = new ProgressDialog(OpenTournamentQuestionIndirectDetailActivity.this);
		
		//전 엑티비티에서 정보 받아오기
		Intent intent = getIntent();
		presentInputRound = intent.getIntExtra("presentInputRound", 0);
		presentHighCategory = intent.getStringExtra("presentHighCategory");
		presentLowCategory = intent.getStringExtra("presentLowCategory");
		presentLowCategoryName = intent.getStringExtra("presentLowCategoryName");
		//presentHighCategory = "lovesituation";
		//presentLowCategory = "date";
		if (isNetworkAvailableAndNotice()) {
			getQuestioinFromServer();
		}
		
		//상단 제목 바꾸기
		TextView tetleLowCategory = (TextView) findViewById(R.id.titleLowCategory);
		tetleLowCategory.setText(presentLowCategoryName);
		
		//클릭 리스너 달기
		RelativeLayout btnGogoBack = (RelativeLayout) findViewById(R.id.btn_goto_back);
		btnGogoBack.setOnClickListener(this);
		
	}
	
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_question_select:
			//버튼의 부모를 받아와서 거기에 속한 질문 영역의 글을 가져옴.
			LinearLayout vQuestionLayout = (LinearLayout) v.getParent();
			TextView vQuestionText = (TextView) vQuestionLayout.findViewById(R.id.question_text);
			presentQuestionText = vQuestionText.getText().toString();
			//이동할 위치 지정
			intentMoveToPage = new Intent(OpenTournamentQuestionIndirectDetailActivity.this,OpenTournamentMainActivity.class);
			//토너먼트 정보 내부 DB 저장
			SharedPreferences pref = getSharedPreferences("tournamentMakeInfo", Activity.MODE_PRIVATE);
			Editor editor = pref.edit();
			switch (presentInputRound) {
			case 1:
				editor.putString("lowCategoryNameRound01", presentLowCategoryName);
				editor.putString("questionTextRound01", presentQuestionText);
				break;
			case 2:
				editor.putString("lowCategoryNameRound02", presentLowCategoryName);
				editor.putString("questionTextRound02", presentQuestionText);
				break;
			case 3:
				editor.putString("lowCategoryNameRound03", presentLowCategoryName);
				editor.putString("questionTextRound03", presentQuestionText);
				break;
			}
			editor.commit();
			startActivity(intentMoveToPage);
			finish();
			break;
		case R.id.btn_goto_back:
			finish();
			break;
		}
	}
	
	
	private void getQuestioinFromServer() {
		new Thread(new Runnable(){
			@Override
			public void run() {
				//UI 를 건들기 때문에 핸들러 사용.
				myHandler.post(new Runnable() {
					@Override
					public void run() {
						
						progressDialog.setMessage("정보를 불러오고 있습니다.");
						progressDialog.show();
						try {
							String jsonText = JsonUtils
									.getStringFromUrl(LovetoConstant.OPEN_TOURNAMENT_QUESTION_DETAIL_URL + "?highCategory=" + presentHighCategory + "&lowCategory=" + presentLowCategory);
							Log.d("tag", jsonText);
							// 원격에서 읽어온 데이터로 JSON 객체 생성
							try {
								Log.d("tag", "제이슨 출발~");
								JSONArray jsonArray = new JSONArray(jsonText);

								for (int i=0;i<jsonArray.length();i++) {
									JSONObject object = jsonArray.getJSONObject(i);
									RelativeLayout qustionLayout = (RelativeLayout) getLayoutInflater()
											.inflate(R.layout.loveto_open_tournament_question_indirect_detail_list, null);
									TextView questionNumber = (TextView) qustionLayout.findViewById(R.id.question_number);
									questionNumber.setText("Q" + (i+1));
									TextView questionText = (TextView) qustionLayout.findViewById(R.id.question_text);
									questionText.setText(object.getString("question_content"));
									RelativeLayout btnQuestionClick = (RelativeLayout) qustionLayout.findViewById(R.id.btn_question_select);
									addOnClickListener(btnQuestionClick);
									Log.d("tag", "질문:" + object.getString("question_content"));
									contentMain.addView(qustionLayout);
								}
								
									
							} catch (JSONException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
							progressDialog.dismiss();
						} catch (UnsupportedEncodingException e) {
							e.printStackTrace();
						}

					}
				});
			}
		}).start();
		
	}
	
	private void addOnClickListener (RelativeLayout layout) {
		layout.setOnClickListener(this);
	}

}
